package com.sword.web;

import com.sword.mapper.UserMapper;
import com.sword.pojo.User;
import com.sword.util.SqlSessionFactoryUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User();
        user.setPassword(password);
        user.setUsername(username);

//
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getsqlSessionFactory();

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User u = mapper.selectByUsername(username);


        if(u == null){
            //如果用户名不存在那么可以添加用户
            mapper.add(user);
            sqlSession.commit();
            sqlSession.close();
        }else{
            //用户名存在，给出提示信息
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();

            writer.write("用户名已存在");
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
